package servlet;

import entity.Blog;
import entity.User;
import service.BlogService;
import service.FollowService;
import service.impl.BlogServiceImpl;
import service.impl.FollowServiceImpl;
import util.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/BlogServlet")
public class BlogServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置解码方式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        HttpSession session=request.getSession();
        //获取值
        String opr=request.getParameter("opr");
        //获取“我的微博”页面搜索框的值
        String content=request.getParameter("content");
        if (content==null){
            content="";
        }
        //获取“首页”页面搜索框的值
        String content3=request.getParameter("content3");
        if (content3==null){
            content3="";
        }

        //创建业务逻辑对象
        BlogService blogService=new BlogServiceImpl();
        FollowService followService=new FollowServiceImpl();

        int uid=((User)session.getAttribute("user")).getId();

        //将微博数、关注数、粉丝数存到session会话当中
        session.setAttribute("blogCount",blogService.getBlogCount(uid));
        session.setAttribute("followCount",followService.getFollowCount(uid));
        session.setAttribute("fansCount",followService.getFansCount(uid));

        //去"我的微博"页面
        if (opr.equals("myBlogList")){
            List<Blog> blogList=blogService.getBlogList(uid,content);
            session.setAttribute("blogList",blogList);
            response.sendRedirect(request.getContextPath()+"/pages/mywb.jsp");
            //去首页
        }else if (opr.equals("HomeBlogList")){
            Page page=new Page();
            //获取当前页面的值
            String pageIndex=request.getParameter("pageIndex");
            if (pageIndex==null){
                pageIndex="1";
            }
            int currPageNo=Integer.parseInt(pageIndex);

            page.setCurrPageNo(currPageNo);


            List<Blog> allblogList=blogService.getAllBlogList(uid,content3,uid,content3,page);
            session.setAttribute("allblogList",allblogList);
            session.setAttribute("page",page);
            response.sendRedirect(request.getContextPath()+"/pages/home.jsp");
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
